// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: leon

#pragma once

#include <boost/algorithm/string.hpp>
#include <map>
#include <nlohmann/json.hpp>
#include <string>
#include <vector>

namespace coin2::exchange::phemex_base::feed_v1 {

using coin2::exchange::feed::WebsocketConfig;

class PhemexRequestGenerator : public base::feed::RequestGenerator {
 public:
  explicit PhemexRequestGenerator(const WebsocketConfig* ws_config)
      : config_(ws_config) {}
  virtual ~PhemexRequestGenerator() = default;

  virtual std::vector<std::string> GenerateRequests(
      const std::vector<std::string>& channels,
      const std::vector<std::string>& symbols,
      const std::map<std::string, std::string>& channel_templates,
      const std::string& request_template) {
    std::vector<std::string> reqs;
    std::vector<std::string> ch = channels;
    auto it = std::find(ch.begin(), ch.end(), "ticker");
    if (it != ch.end()) {
      const auto& channel_name = *it;
      std::string c = channel_templates.at(channel_name);
      std::string s = request_template;
      boost::replace_all(s, "{channel}", c);
      boost::replace_all(s, "\"{}\"", "");
      reqs.push_back(s);
      ch.erase(it);
    }

    std::vector<std::string> reqs_kline;
    std::vector<std::string> ch_kline;
    auto iter = ch.begin();
    while (iter != ch.end()) {
      if (StringStartsWith(*iter, "kline_rest")) {
        ch_kline.push_back(*iter);
        iter = ch.erase(iter);
      } else {
        iter++;
      }
    }
    if (!ch_kline.empty()) {
      auto timestamp = MarketTimestampProvider::GetTimestamp();
      boost::posix_time::ptime round_time = TimestampRoundHour(timestamp);
      for (auto& ch_k : ch_kline) {
        std::string c = channel_templates.at(ch_k);
        auto interval_time = GetGranularity(c);
        for (auto& symbol : symbols) {
          std::vector<std::pair<int64_t, int64_t>> durations;
          bool long_query = base::feed::RequestGenerator::CheckLongQuery(
              round_time, symbol, ch_k, &last_long_query_time_);
          if (long_query) {
            durations = base::feed::RequestGenerator::GetDurations(
                config_->kline_length(), config_->kline_start(), config_->kline_end(),
                interval_time, 995);
          } else {
            // query small data
            durations = base::feed::RequestGenerator::GetDurations(
                "3", "", "",interval_time, 900);
          }
          CHECK((durations.size() == 1) && (timestamp - 1000 * interval_time) < durations[0].first)
              << "Phemex kline query too long, official API only support 1000 limit.";

          std::string c_copy = c;
          boost::replace_all(c_copy, "{}", symbol);
          reqs_kline.emplace_back(c_copy);
        }
      }
    }
    reqs.insert(reqs.end(), reqs_kline.begin(), reqs_kline.end());

    for (const auto& channel_name : ch) {
      for (const auto& symbol : symbols) {
        std::string c = channel_templates.at(channel_name);
        std::string s = request_template;
        boost::replace_all(s, "{channel}", c);
        boost::replace_all(s, "{}", symbol);
        reqs.push_back(s);
      }
    }
    return reqs;
  }

 private:
  int64_t GetGranularity(const std::string& channel) {
    if (channel.find("&resolution=60&") != std::string::npos) {
      return (int64_t)60 * 1'000'000'000;
    } else if (channel.find("&resolution=300&") != std::string::npos) {
      return (int64_t)5 * 60 * 1'000'000'000;
    } else if (channel.find("&resolution=900&") != std::string::npos) {
      return (int64_t)15 * 60 * 1'000'000'000;
    } else if (channel.find("&resolution=3600&") != std::string::npos) {
      return (int64_t)60 * 60 * 1'000'000'000;
    } else if (channel.find("&resolution=86400&") != std::string::npos) {
      return (int64_t)24 * 3600 * 1'000'000'000;
    } else {
      THROW() << "Unkonw new channel: " << channel;
    }

    return std::numeric_limits<int64_t>::quiet_NaN();
  }

  const WebsocketConfig* config_;
};

}  // namespace coin2::exchange::phemex_base::feed_v1
